package common;

import io.github.bonigarcia.wdm.WebDriverManager;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.PageLoadStrategy;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.edge.EdgeOptions;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.Duration;

public class Utils {
    public static WebDriver driver = null;
    protected static WebDriverWait wait = null;
    protected static String detailUrl = "http://8.137.19.140:9090/blog_detail.html?blogId=91389";
    public Utils(String URL) {
        driver = createDriver();
        driver.get(URL);
        wait = new WebDriverWait(driver,Duration.ofSeconds(15));
    }

    /**
     * 获取驱动对象
     * @return
     */
    public static WebDriver createDriver() {
        if(driver == null) {
            //驱动程序自动化
            WebDriverManager.edgedriver().setup();
            EdgeOptions options = new EdgeOptions();
            //允许访问所有链接
            options.addArguments("--remote-allow-origins=*");
            options.setPageLoadStrategy(PageLoadStrategy.NONE);
            //创建驱动对象
            driver = new EdgeDriver(options);
            //设置隐式等待时间 -- 3s
            driver.manage().timeouts().implicitlyWait(Duration.ofMillis(5));
        }
        return driver;
    }

    /**
     * 打印格式：
     *        ./src/test/java/images/yyyy-MM-dd/
     *                  文件夹：yyyy-MM-dd
     *                          method-HHmmssSS.png
     *                   文件夹：yyyy-MM-dd
     *                          method-HHmmssSS.png
     */
    protected void ScreenShot(String methodName) throws IOException {
        SimpleDateFormat sim1 = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat sim2 = new SimpleDateFormat("HHmmssSS");
        String dirTime = sim1.format(System.currentTimeMillis());
        String fileTime = sim2.format(System.currentTimeMillis());
        String fileName = "./src/test/java/images/" + dirTime + "/" + methodName + "-" + fileTime + ".png";
        File srcFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
        FileUtils.copyFile(srcFile,new File(fileName));
    }

    public static void quit() {
        driver.quit();
    }
}
